package com.dwxt.community.service;

import com.alibaba.fastjson.JSONObject;
import com.dwxt.common.base.BaseResult;
import com.dwxt.common.util.OkHttpUtils;
import com.dwxt.community.dao.UserMapper;
import com.dwxt.community.entity.User;
import com.dwxt.community.entity.vo.UserVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class AsyncService {

    @Value("${dongMei.url}")
    private String dongMeiUrl;

    @Autowired
    private UserMapper userMapper;

    @Async("myExecutor")
    public void dongMeiRegisterAndLogin(String id, String phone, String password) {
        //动美网注册
        JSONObject result = dongMeiRegister(phone, password);
        int errorcode1 = result.getInteger("errorcode");
        if (errorcode1 != 0) {
            log.error("{},result========>" + result, phone);//return BaseResult.build(result.getInteger("errorcode"),
            return;
        }
        //动美网登录，获取动美的userId
        JSONObject object = loginDongMeiWang(phone, password);
        //JSONObject object = JSONObject.fromObject(res);
        int errorcode2 = object.getInteger("errorcode");
        if (errorcode2 != 0) {
            log.error("{},object========>" + object, phone);
            return;
        }
        String dongMeiUserId = object.getJSONObject("value").getString("Id");
        User user = new User();
        user.setId(id);
        user.setDongMeiId(dongMeiUserId);
        userMapper.updateByPrimaryKeySelective(user);
    }

    public JSONObject dongMeiRegister(String phone, String password) {
        String url = dongMeiUrl + "Register";
        Map<String, String> params = new HashMap<>();
        params.put("username", phone);
        params.put("password", password);

        Map<String, String> headers = new HashMap<>();
        headers.put("username", "15123058497");
        headers.put("Signature", "2ddfeb530a2e81c9f45ed37398e6a20ec357d1c9");
        return JSONObject.parseObject(OkHttpUtils.formPost(url, params, headers));
    }

    /**
     * 登录动美网
     *
     * @param phone
     * @param password
     * @return
     */
    public JSONObject loginDongMeiWang(String phone, String password) {
        String url = dongMeiUrl + "UserLogin";
        Map<String, String> params = new HashMap<>();
        params.put("username", phone);
        params.put("password", password);
        return JSONObject.parseObject(OkHttpUtils.formPost(url, params, null));
    }
}
